// asynchronous progress/cancel support
define(
		["require", 
		   "jquery",
		   "bip.base",
		   "bip.cache",
		   "bip.async",
		   "typeahead",
		   "hogan"
		   ],
  function(require) {
    "use strict";

    var $ = require("jquery");
    var $bip = require("bip.base");
    
    var _userOrGroupTemplate = "";
    _userOrGroupTemplate += '<p><strong>';
    _userOrGroupTemplate += '{{#group}}<i class="icon-usergroup"></i>{{/group}}';
    _userOrGroupTemplate += '{{^group}}<i class="icon-user"></i>{{/group}}';
    _userOrGroupTemplate += '&nbsp;{{value}}</strong></p>';
    
    function initUser(inputID, data){
    	init(inputID, data, _userOrGroupTemplate);
    }
    
    function initUserAndGroup(inputID, data){
    	init(inputID, data, _userOrGroupTemplate);
    }
    
    function initGroup(inputID, data){
    	init(inputID, data, _userOrGroupTemplate);
    }
    
    function init(inputID, data, template){
    	$('#' + inputID).typeahead({
    		  name: inputID + new Date().getTime(),
    		  minLength : 0,
    		  limit: 10,
    		  local: data,
    		  template : template,                                                               
    		  engine: Hogan   
    	});
    	
    	bindEvent(inputID);
    }
    
    function bindEvent(inputID){
    	$("#" + inputID).bind("typeahead:selected", function(event, data, name){
	    	var tmp = JSON.stringify(data);
	    	
	    	$("#" + inputID).attr("data", tmp);
	    });
    }
    
    function destroy(inputID){
    	$('#' + inputID).typeahead('destroy');
    }
    
    var autocomplete = {
    	initUser : initUser,
    	initGroup : initGroup,
    	initUserAndGroup : initUserAndGroup,
    	destroy : destroy
    };
    
    return autocomplete;
  }
);

